#include "Dispatcher.h"
#include <assert.h>

bool Dispatcher::addTask(co_overlap task)
{
	_taskMap[task.getSocket()].reset(new co_overlap(std::move(task)));
	return true;
}

bool Dispatcher::isNewTask(uint64_t socket) const
{
	return _taskMap.find(socket) == _taskMap.end();
}

bool Dispatcher::runTask(uint64_t socket, bool isDoneRemove)
{
	auto itf = _taskMap.find(socket);
	if (itf == _taskMap.end()) {
		_readyHandleList.push_back(socket);
		return false;
	}

	runTask(itf->second.get());

	if(isDoneRemove && itf->second->done()) {
		_taskMap.erase(itf);
	}

	return true;
}

bool Dispatcher::runTask(co_overlap* task)
{
	task->resume();
	return true;
}

bool Dispatcher::removeTask(uint64_t socket)
{
	auto itf = _taskMap.find(socket);
	if (itf == _taskMap.end()) {
		return false;
	}

	assert(itf->second->done());

	_taskMap.erase(itf);

	return true;
}
